import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as multer from 'multer';

@Injectable()
export class FileUploadMiddleware implements NestMiddleware {
    private upload: any;

    constructor() {
        this.upload = multer({
            storage: multer.memoryStorage(),
            limits: {
                fileSize: 5 * 1024 * 1024, // 5MB
            },
        }).any();
    }

    use(req: Request, res: Response, next: NextFunction) {
        this.upload(req, res, (err: any) => {
            if (err instanceof multer.MulterError) {
                return res.status(400).json({
                    message: 'File upload error',
                    error: err.message,
                });
            } else if (err) {
                return res.status(500).json({
                    message: 'Internal server error during file upload',
                    error: err.message,
                });
            }
            next();
        });
    }
} 